package cn.fl.ref.fribaseinfo.controller;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import cmm.comm.facade.framework.api.ISysDictionaryApiService;
import cmm.mid.core.framework.page.DataResultVO;
import cmm.mid.core.framework.page.KeyValueVO;
import cmm.mid.core.framework.page.ListPageVO;
import cmm.mid.core.framework.page.Pager;
import cmm.web.core.framework.controller.BaseController;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.constant.BaseExceptionConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.CollectionUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.framework.constant.DictionaryConstant;
import cn.fl.ref.fribaseinfo.service.IFriBaseInfoService;
import cn.fl.ref.fribaseinfo.service.IFundInsSimilarInfoService;
import cn.fl.ref.fribaseinfo.service.IFundRasInsLimService;
import cn.fl.ref.fribaseinfo.transform.FundInsSimilarInfoVOTransform;
import cn.fl.ref.fribaseinfo.vo.BankAccInfoVO;
import cn.fl.ref.fribaseinfo.vo.FriBaseInfoVO;
import cn.fl.ref.fribaseinfo.vo.FundInsSimilarInfoVO;
import cn.fl.ref.fribaseinfo.vo.FundRasInsLimVO;
import fl.ref.crbaseinfo.service.ICrBaseInfoApiService;
import fl.ref.fribaseinfo.condition.FundInsSimilarInfoQueryCondition;
import fl.ref.fribaseinfo.condition.FundRasInsLimQueryCondition;
import fl.ref.fribaseinfo.constant.FriBaseInfoConstant;
import fl.ref.fribaseinfo.dto.FriBaseInfoDTO;
import fl.ref.fribaseinfo.dto.FundInsSimilarInfoDTO;

/**
 * @Description: 资管机构相似度信息表
 * @author gengchunlan
 * @date 20200208
 */
@Controller
@RequestMapping("/rfbase/fundInsSimilarInfo")
public class FundInsSimilarInfoController extends BaseController {

	private static final Logger logger = LoggerFactory.getLogger(FundInsSimilarInfoController.class);

	@Autowired
	private IFriBaseInfoService friBaseInfoService;
	/**
	 * 数据字典服务
	 */
	@Autowired
	private ISysDictionaryApiService sysDictionaryApiService;
	/**
	 * 资管机构相似度
	 */
	@Autowired
	private IFundInsSimilarInfoService fundInsSimilarInfoService;

	@Autowired
	private IFundRasInsLimService fundRasInsLimService;
	/**
	 * 到列表页面
	 */
	@RequestMapping(value = "/toListPage.do", method = { RequestMethod.GET })
	public ModelAndView toListPage(HttpServletRequest request, HttpServletResponse response) {
		logger.info("加载资管机构相似度信息列表页面.");
		ModelAndView view = new ModelAndView("rfbase/fribaseinfo/fundInsSimilarInfoList");
		String mainFundInsId = request.getParameter("mainFundInsId");
		if(StringUtils.isNotBlank(mainFundInsId)) {
			view.addObject("mainFundInsId", mainFundInsId);
			//金融机构
			FriBaseInfoVO vo=friBaseInfoService.selectById(Long.parseLong(mainFundInsId), CurrentThreadContext.getCurrentSysCd(),
					CurrentThreadContext.getCurrentOrgCd());
			view.addObject("friBase", vo);
			//金融机构相似度优先级
			FundInsSimilarInfoQueryCondition qc = new FundInsSimilarInfoQueryCondition();
			qc.setMainFundInsId(Long.parseLong(mainFundInsId));
			qc.setYesFlag("1");//查询主机构  默认 1 
			List<FundInsSimilarInfoVO> list=fundInsSimilarInfoService.searchList(qc);
			if(list!=null && list.size()>0) {
				FundInsSimilarInfoVO svo=list.get(0);
				view.addObject("zgNum",svo.getZgNum());
			}
			if(true) {//获取机构限额信息
				//项目类型名称
				Map<String, String> prjTypCdMap = sysDictionaryApiService.searchGroupToMapAll(CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd(), DictionaryConstant.CODE_PRJ_TYPE_CD); 
				FundRasInsLimQueryCondition fundRasInsLimQueryCondition = new FundRasInsLimQueryCondition();
				fundRasInsLimQueryCondition.setInsId(mainFundInsId);
				List<FundRasInsLimVO> fundRasInsLimList = fundRasInsLimService.searchList(fundRasInsLimQueryCondition);
				BaseLogUtils.info(logger, null, "fundRasInsLimList:" + JSONObject.toJSONString(fundRasInsLimList), CurrentThreadContext.getCurrentUserName());
				//数据转换
				if(CollectionUtils.isNotEmpty(fundRasInsLimList)) {
					List<Map<String, Object>> fundRasInsLimMapList = new ArrayList<Map<String, Object>>(fundRasInsLimList.size());
					for (FundRasInsLimVO fundRasInsLim : fundRasInsLimList) {
						Map<String, Object> fundRasInsLimMap = new HashMap<String, Object>();
						//设置项目类型
						if(prjTypCdMap != null && prjTypCdMap.size() >0) {
							if (prjTypCdMap.containsKey(fundRasInsLim.getPrjTypCd())) {
								fundRasInsLimMap.put("PRJ_TYP", prjTypCdMap.get(fundRasInsLim.getPrjTypCd()));
		                    }
						}
						
						Double insLimAmt = fundRasInsLim.getInsLimAmt();
						fundRasInsLimMap.put("INS_LIM_AMT_",(insLimAmt == null || insLimAmt ==0)?"无":insLimAmt.toString());
						
						Long insLimMum = fundRasInsLim.getInsLimNum();
						fundRasInsLimMap.put("INS_LIM_NUM_",(insLimMum == null || insLimMum ==0)?"无":insLimMum.toString());
						
						fundRasInsLimMapList.add(fundRasInsLimMap);
					}
					//设置页面显示数据
					if(CollectionUtils.isNotEmpty(fundRasInsLimMapList)) {
						vo.setFundRasInsLimList(fundRasInsLimMapList);
					}//end //获取机构限额信息
				}//判空
				
			}
		}
		BaseLogUtils.info(logger, "toListPage", "资管机构相似度查询数据完成. DATA:" + JSONObject.toJSONString(mainFundInsId),
				CurrentThreadContext.getCurrentUserName());
		return view;
	}
	/**
	 * 初始化列表
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/initList.do", method = { RequestMethod.GET })
	@ResponseBody
	public Object initList(HttpServletRequest request, HttpServletResponse response) {
		//String currentPage = request.getParameter("page");
		//String pageSize = request.getParameter("pagesize");
		String mainFundInsId = request.getParameter("mainFundInsId");// 融资机构id
		/*
		 * if (StringUtils.isNotEmpty(currentPage)) {
		 * page.setCurrentPage(Integer.parseInt(currentPage)); }
		 * 
		 * if (StringUtils.isNotEmpty(currentPage)) {
		 * page.setEveryPage(Integer.parseInt(pageSize)); }
		 */
		FundInsSimilarInfoQueryCondition qc = new FundInsSimilarInfoQueryCondition();
		if (StringUtils.isNotEmpty(mainFundInsId)) {
			qc.setMainFundInsId(Long.parseLong(mainFundInsId));;
		}
		qc.setSysCd(CurrentThreadContext.getCurrentSysCd());
		qc.setOrgCd(CurrentThreadContext.getCurrentOrgCd());
		qc.setNoFlag("1"); //不查询主机构  默认 1 
		
		List<FundInsSimilarInfoVO> voList = this.fundInsSimilarInfoService.searchList(qc);
		//设置数据字典
		this.setFriSimilarInfo(voList, CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd()); 
		ListPageVO<FundInsSimilarInfoVO> listPage = new ListPageVO<FundInsSimilarInfoVO>(voList, voList.size());

		BaseLogUtils.info(logger, "initList", "查询数据完成. DATA:" + JSONObject.toJSONString(mainFundInsId),
				CurrentThreadContext.getCurrentUserName());
		return listPage;
	}
	/**
	 * 账户排序
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/changeNum.do", method = { RequestMethod.GET , RequestMethod.POST} )
	@ResponseBody
	public Object changeNum(HttpServletRequest request, HttpServletResponse response) {
		String id = request.getParameter("id");
		String num = request.getParameter("num");
		String mainFundInsId = request.getParameter("mainFundInsId");//主机构id
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, "新增成功!");
		BaseLogUtils.info(logger, "changeNum",CurrentThreadContext.getCurrentUserName());
		Map<Object,String> map=new HashMap<Object,String>();
		if(StringUtils.isNotBlank(id)){
			map.put("id", id);	
		}
		if(StringUtils.isNotBlank(num)) {
			map.put("num", num);	
		}
		if(StringUtils.isNotBlank(mainFundInsId)) {
			map.put("mainFundInsId", mainFundInsId);	
		}
		try {
			if(map.containsKey("id") && map.containsKey("num") && map.containsKey("mainFundInsId")) {
				this.fundInsSimilarInfoService.changeNum(map);
			}
			result.setSuccess(BaseConstant.IS_YESNO_YES);
			result.setInfo("成功!");
			BaseLogUtils.info(logger, "changeNum", "数据 , ID:" + id, CurrentThreadContext.getCurrentUserName());
		} catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "changeNum", "失败," + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		} catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("失败!");
			BaseLogUtils.error(logger, "changeNum", "失败," + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}
	private void setFriSimilarInfo(List<FundInsSimilarInfoVO> listVO, String sysCd, String orgCd) {
		//REQ-13543 业务线
		Map<String, String> bussLineCdMap = this.sysDictionaryApiService.searchGroupToMap(sysCd, orgCd,
				FriBaseInfoConstant.FUND_BUSSINESS_LINE);
		for (FundInsSimilarInfoVO fundSimilarInfo : listVO) {
			//业务线bussLineCdMap
			if(StringUtils.isNotEmpty(fundSimilarInfo.getBussinessLine())) {
				if(bussLineCdMap.containsKey(fundSimilarInfo.getBussinessLine())) {
					fundSimilarInfo.setBussinessLineNm(bussLineCdMap.get(fundSimilarInfo.getBussinessLine()));
				}
			}
			
		}
	}
	

}
